/*
 * Copyright (C) 2018 guomw.Inc. All rights reserved.
 * 项目名称： report-manage
 * 文件名称： IndexController.java
 * Date：18-11-5 上午11:10
 * Author: guomw
 */

package com.guomw.report.web.controller;

import com.guomw.report.common.utils.RandomUtils;
import com.guomw.report.service.annotations.OperatorId;
import com.guomw.report.service.entity.SystemManager;
import com.guomw.report.service.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.Random;

/**
 * @author guomw
 * @date 2018/9/6
 */
@Controller
public class IndexController {

    @Autowired
    private SystemService systemService;

    @RequestMapping(value = {"index", "/","login"})
    public String index() {
        return "index";
    }


    @RequestMapping("home")
    public String home(@OperatorId Integer operatorId, Model model) {
        SystemManager manager= systemService.findManagerById(operatorId);
        if(manager!=null) {
            model.addAttribute("userName", manager.getLoginName());
        }
        return "main";
    }

    @RequestMapping("/bank")
    public String bank() {
        return "bank";
    }

    @RequestMapping("desktop")
    public String desktop(){
        return "desktop";
    }

    /**
     * 登录
     *
     * @return
     */
    @RequestMapping(value = "/doLogin", method = RequestMethod.POST)
    public String doLogin(@RequestParam String loginName,
                          @RequestParam String loginPwd,
                          @RequestParam String verifyCode,
                          HttpServletRequest request) throws UnsupportedEncodingException {

        if (!verifyCode.toLowerCase().equals(request.getSession().getAttribute("verifyCode").toString().toLowerCase())) {
            return "redirect:/login?error=2";
        }
        SystemManager manager = systemService.findManagerByLoginName(loginName);
        if (manager != null) {
            if (manager.getLoginPwd().equals(DigestUtils.md5DigestAsHex(loginPwd.getBytes("UTF-8")).toLowerCase())) {
                if (manager.isEnable()) {
                    HttpSession session = request.getSession(true);
                    session.setAttribute("OwnerId", manager.getUserId());
                    //设置
                    manager.setLastLoginTime(LocalDateTime.now());
                    systemService.saveManager(manager);
                    return "redirect:/home";
                } else {
                    //账户已被禁用
                    return "redirect:/login?error=4";
                }
            } else {
                return "redirect:/login?error=3";
            }
        }
        return "redirect:/login?error=1";
    }

    /**
     * 退出注销
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "redirect:/login";
    }


    /**
     * 获取图片验证码
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = {"/verifyCode"}, method = RequestMethod.GET)
    public void verifyCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 创建一张空白的图片
        BufferedImage image = new BufferedImage(100, 30, BufferedImage.TYPE_INT_RGB);
        // 获取该图片的笔画
        Graphics g = image.getGraphics();

        // 绘制背景
        // 设置画笔的颜色
        Random r = new Random();
        g.setColor(new Color(249, 249, 250));
        // 绘制一个实心额矩形区域
        g.fillRect(0, 0, 100, 30);
        // 绘制内容
        g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
        g.setFont(new Font(null, Font.BOLD, 25));

        // 生成验证码
        String num = RandomUtils.randomNumber(5);

        // 验证码的内容保存到session中
        HttpSession session = request.getSession();
        System.out.println(session.getId());
        session.setAttribute("verifyCode", num);
        FontMetrics fontMetrics = g.getFontMetrics();
        int stringWidth = fontMetrics.stringWidth(num);
        int stringAscent = fontMetrics.getAscent();
        int stringDescent = fontMetrics.getDescent();
        //设置内容居中
        g.drawString(num, 100 / 2 - stringWidth / 2, 30 / 2 + (stringAscent - stringDescent) / 2);

        // 将内存中的图片发送到客户端
        response.setContentType("image/jpg");
        OutputStream ops = response.getOutputStream();
        ImageIO.write(image, "jpeg", ops);
    }
}
